<template>
<!-- 自动监听 -->
自动监听
  <input type="text" v-model="query" />
  <!-- 按钮触发 -->
  按钮触发
  <input type="text" v-model="input" />
  <button @click="setQuery">搜索</button>
  <div v-if="loading">Loading ...</div>
  <div v-else-if="error">Something went wrong ...</div>
  <ul v-else>
    <li
      v-for="item of hits"
      :key="item.objectID"
    >
      <a :href="item.url">{{item.title}}</a>
    </li>
  </ul>
</template>

<script lang="ts">
import { reactive, onMounted, watchEffect, toRefs } from 'vue'

export default {
  setup() {
    const state = reactive({
      hits: [],
      query: 'vue',
      input: 'vue',
      error: false,
      loading: false,
    })
    const fetchData  = async( query: string ) =>{
      state.error = false
      state.loading = true
      try{
        const data = await fetch(
        `https://hn.algolia.com/api/v1/search?query=${ query }`
      ).then(rsp => rsp.json())
      state.hits = data.hits
      }catch{
        state.error = true
      }
      state.loading = false
    }
    // 按钮点击方法
    const setQuery = () => {
      state.query = state.input
    }
    onMounted(() =>{
      watchEffect(() =>{
        if (state.query === 'vue3') {
    // 当 query 为 vue3 时，停止监听
    stop()
  }
        fetchData(state.query)
      })
    })
    return { ...toRefs(state), setQuery}
  }
}
</script>